<template>
  <div class="article-page">
    <div class="lg-container">
      <div class="lg-row">
        <div class="article-sidebar lg-col-md-15">
          <user-info
            :statistics-info="statisticsInfo"
            style="margin-bottom: 20px"
          ></user-info>
          <type-list></type-list>
        </div>
        <div class="article-container lg-col-md-45">
          <article-list
            :data="articleList"
            :load="initLoad"
            :loading="loading"
            :disabled="disabled"
            :no-more="noMore"
          ></article-list>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import UserInfo from '@/components/page/UserInfo/index.vue'
import ArticleList from '@/components/page/ArticleList/index.vue'
import TypeList from '@/components/page/TypeList/index.vue'
import { useAppStore } from '@/store/useAppStore'
export default {
  name: 'ArticlePage',
  components: {
    UserInfo,
    ArticleList,
    TypeList,
  },
  setup() {
    const statisticsInfo = ref()
    const articleList = ref([])
    const proxy = getCurrentInstance().proxy
    const appStore = useAppStore()

    const state = reactive({
      pageNum: 1,
      pageSize: 10,
      count: 0,
    })
    const loading = ref(true)
    const noMore = computed(
      () => articleList.value.length >= state.count && !loading.value
    )
    const disabled = computed(() => loading.value || noMore.value)
    async function initLoad() {
      loading.value = true
      try {
        const res = await proxy.$API.article.page({
          pageNum: state.pageNum,
          pageSize: state.pageSize,
          status: 'Published',
        })
        if (state.pageNum === 1) {
          articleList.value = res.data.list
        } else {
          articleList.value = articleList.value.concat(res.data.list)
        }

        state.count = res.data.count

        // 下一页
        if (!noMore.value) {
          state.pageNum += 1
        }
      } catch (error) {

      } finally {
        loading.value = false
      }
    }
    onMounted(async () => {
      // 请求typeList
      if (!appStore.typeList.length) {
        await appStore.getTypeList(proxy)
      }
      await initLoad()
    })
    return {
      statisticsInfo,
      articleList,
      initLoad,
      loading,
      disabled,
      noMore,
    }
  },
  async asyncData({ app }) {
    try {
      const res = await app.$API.user.getStatistics()
      return {
        statisticsInfo: res.data
      }
    } catch (error) {
      return {
        statisticsInfo: {
          articleCount: 0,
          tagCount: 0,
          typeCount: 0,
        }
      }
    }
  },
}
</script>

<style lang="less">
.article-page {
  height: 100%;
  .article-sidebar {
    margin-bottom: 20px;
    display: none;
    @media screen and (min-width: @breakpoints-md) {
      display: block;
    }
  }
}
</style>
